package com.chy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chy.common.CustomException;
import com.chy.common.R;
import com.chy.entity.Range;
import com.chy.mapper.RangeMapper;
import com.chy.service.RangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class RangeServiceImpl extends ServiceImpl<RangeMapper, Range> implements RangeService {

    @Autowired
    private RangeMapper rangeMapper;
    @Override
    public Page getRangeList(Map<String, Object> params) {
        Integer page = (Integer) params.get("page");
        Integer pageSize = (Integer) params.get("pageSize");
        String name = (String) params.get("name");
        Page<Range> rangePage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Range> rangeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        rangeLambdaQueryWrapper.like(name != null, Range::getRangeName, name).orderByDesc(Range::getRouterLevel);
        rangeMapper.selectPage(rangePage, rangeLambdaQueryWrapper);
        return rangePage;
    }

    @Override
    public R addRange(Map<String, Object> params) {
        Range range = JSON.parseObject(JSON.toJSONString(params), Range.class);
        LambdaQueryWrapper<Range> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(range.getRangeName() != null, Range::getRangeName, range.getRangeName());
        Range one = this.getOne(wrapper);
        if(one != null){
            throw new CustomException("权限名称已存在！");
        }
        return this.save(range) ? R.success() : R.error();
    }
}
